package com.gandong8.derby.core.handler;

import cn.hutool.json.JSONUtil;
import com.gandong8.derby.core.constant.DOConstant;
import com.gandong8.derby.core.exception.CommonException;
import com.gandong8.derby.core.exception.ErrorException;
import com.gandong8.derby.core.exception.LoginException;
import com.gandong8.derby.core.exception.LoginRedirectException;
import com.gandong8.derby.core.response.ResponseData;
import com.gandong8.derby.core.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 异常全局处理
 * @author xiaoyutou
 */
@Slf4j
@ControllerAdvice
public class WebExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object otherHandler(Exception e) throws Exception {
        log.error("exception", e);
        return ResponseData.fail(e.getMessage());
    }

    /**
     * 如果用@RequestBody注解做提交json字符串自动绑定到pojo入参时，需要是"application/json;charset=UTF-8"
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Object mediaTypeNotSupportHandler(HttpMediaTypeNotSupportedException e) throws Exception {
        return ResponseData.fail("content type error");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Object notFountHandler(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("404.html");
        return modelAndView;
    }

    @ExceptionHandler(ErrorException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object errorHandler(ErrorException e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.setViewName("error.html");
        return modelAndView;
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Object methodNotSupportedHandler(HttpRequestMethodNotSupportedException e){
        return ResponseData.fail(e.getMessage());
    }

    @ExceptionHandler(value = CommonException.class)
    @ResponseBody
    public Object commonHandler(CommonException e) throws Exception {
        log.error("exception", e);
        return ResponseData.fail(e.getMessage());
    }

    /**
     * 一般是@RequestBody注解做提交json字符串自动绑定到pojo入参时，提交的数据不是json字符串格式，或解析出错
     * @param e
     * @return
     * @throws Exception
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public Object notReadableHandler(HttpMessageNotReadableException e) throws Exception {
        return ResponseData.fail("JSON parse error");
    }
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = LoginException.class)
    @ResponseBody
    public ResponseData notLoginHandler(LoginException e) throws Exception {
        return ResponseData.login();
    }

    @ExceptionHandler(value = LoginRedirectException.class)
    public String notLoginHandler(LoginRedirectException e) throws Exception {
        return "redirect:"+ DOConstant.LOGIN_PATH+"?code="+e.getCode();
    }

    /**
     * Get请求 使用Validated或@Valid 实体校验失败后抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseData bindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return ResponseData.fail(message);
    }
    /**
     * POST请求 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseData methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        //message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResponseData.fail(message);
    }


    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseData constraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return ResponseData.fail(message);

    }


}
